<template>
  <div class="container">
    <el-form ref="loginForm" :model="formData" :rules="rules" label-width="auto" hide-required-asterisk>
      <h2>十方智育-后台登陆</h2>
      <el-form-item label="账 号" prop="username">
        <el-input v-model="formData.username" placeholder="请输入账号" :prefix-icon="User" />
      </el-form-item>
      <el-form-item label="密 码" prop="userpwd">
        <el-input v-model="formData.userpwd" type="password" placeholder="请输入密码" :prefix-icon="Lock" show-password />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(loginForm)" style="margin-left:42px;">登录</el-button>
        <el-button @click="resetForm(loginForm)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { getCurrentInstance, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const loginForm = ref<FormInstance>()
const formData = reactive({
  username: '',
  userpwd: ''
})

const rules = reactive<FormRules>({
  username: [
    { required: true, message: '账号不能为空', trigger: 'blur' },
    { min: 4, max: 20, message: '账号长度必须是4到20位字符', trigger: 'blur' },
  ],
  userpwd: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, message: '密码至少是6位字符', trigger: 'blur' },
  ]
})

const axios = getCurrentInstance()?.appContext.config.globalProperties.axios
const router = useRouter()

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
		  console.log(formData.username)
		  console.log(formData.userpwd)
        const resp = await axios.get(`sysUser/login?username=${formData.username}&userpwd=${formData.userpwd}&source=1`)
        if (resp.code === 200) {
          ElMessage.success('登录成功')
          sessionStorage.setItem('loginUser', JSON.stringify(resp.data))
          router.replace('/index')
        } else {
          ElMessage.error(resp.data.msg || '账号密码错误！')
        }
      } catch (e) {
        ElMessage.error('登录请求失败，请检查网络或联系管理员')
      }
    } else {
      ElMessage.error('请输入正确账号和密码')
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped>
.container {
  height: 100vh;
  background: url('../assets/login.webp') no-repeat center;
  background-size: cover;
  position: relative;
}
.el-form {
  width: 550px;
  background: rgba(255, 255, 255, 0.5);
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  padding: 30px 50px;
  border-radius: 20px;
}
.el-form h2 {
  text-align: center;
}
</style>